package com.guigu.mq.listener;

import com.guigu.mq.feign.OrderFeign;
import com.guigu.tms.result.R;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName:PayListener
 * @Description:接收支付消息
 * @Author:taoLong
 * @Date:2021/11/17:9:36 星期三
 * @email:2391611102@qq.com or 2391611102qq@gmail.com
 */
@Component
public class PayListener {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private OrderFeign orderFeign;

    private Logger log = LoggerFactory.getLogger(PayListener.class);

    @RabbitListener(queues = "diedQueue", ackMode = "MANUAL")
    public void onMessage(Message message, Channel channel) throws IOException {
        String messageId = message.getMessageProperties().getMessageId();
        String id = (String) redisTemplate.opsForValue().get(messageId);
        if (StringUtils.isBlank(id)) {
            /**
             * 如果在缓存中没有,那么该消息是被消费过了,需要做其他操作,直接应答即可
             */
            log.error("已经消费过了,无需再消费!");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        String orderId = new String(message.getBody(),StandardCharsets.UTF_8);
        log.info("orderId为:{}", orderId);
        R r = orderFeign.changeOrderTimeout(orderId);
        log.info("订单超时的结果为:{}", r);
        Boolean flag = redisTemplate.delete(messageId);
        if (flag) {
            log.info("删除成功!");
        } else {
            log.error("删除失败!");
        }
        /**
         * 开始应答
         */
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
